package ua.org.nuos.sdms.clientgui.client.view.selectGroup;

import com.vaadin.data.Validator;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.*;
import ua.org.nuos.sdms.clientgui.client.components.factory.ButtonFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.FormFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.LayoutFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.WindowFactory;
import ua.org.nuos.sdms.clientgui.client.components.fieldFactory.GroupFieldFactory;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.CreateNewGroupEvent;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 04.03.12
 * Time: 17:09
 * To change this template use File | Settings | File Templates.
 */
public class CreateGroupComponent extends VerticalLayout {

    public static final String ID = CreateGroupComponent.class.getSimpleName();

    private BeanItem<Group> groupBeanItem;
    private Form form;

    public CreateGroupComponent() {
        init();
    }

    private void init() {
        setSizeFull();
        AppProxy.getInstance().getComponentLocator().addContainer(ID, this);

        groupBeanItem = new BeanItem<Group>(new Group());

        form = FormFactory.getForm(new GroupFieldFactory(), groupBeanItem, new String[]{"name", "organisation", "about"});
        form.setSizeFull();

        Layout buttons = getButtonsLayout();

        addComponent(form);
        addComponent(buttons);
        setComponentAlignment(buttons, Alignment.BOTTOM_RIGHT);
    }

    private Layout getButtonsLayout() {
        Button close = WindowFactory.getCloseButton(
                AppProxy.getInstance().getComponentLocator().getWindow(SelectGroupWindow.ID).getWindow(), "Не стоит");
        Button register = ButtonFactory.getButton("Создать группу", getRegisterClickListener());
        return LayoutFactory.getHLayout(register, close);
    }

    private Button.ClickListener getRegisterClickListener() {
        return new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    form.commit();
                    Group group = groupBeanItem.getBean();
                    CreateNewGroupEvent ev = new CreateNewGroupEvent(group);
                    AppProxy.getInstance().getController(GlobalBoard.ID).fire(ev);
                } catch (Validator.InvalidValueException e) {
                    Logger.getAnonymousLogger().log(Level.WARNING, "validation exception", e);
                }
            }
        };
    }
}
